<?php

set_time_limit(0);

require 'libs/PHPWebSocket.php';

/**
* Test Class
*/
class TestWebSocket
{
    private $socket;

    /**
     * construct function
     */
    function __construct(PHPWebSocket $socket)
    {
        $this->socket = $socket;
    }

    public function startServer($host, $port)
    {
        $this->socket->wsStartServer($host, $port);
    }

    public function binds($bindArr)
    {
        foreach ($bindArr as $key => $bind) {
            $this->socket->bind($key, $bind);
        }
    }

    public function onOpen($clientId)
    {
        $ip = long2ip($this->socket->wsClients[$clientId][6]);

        $this->socket->log("{$ip} ({$clientId}) has connected.");

        $clients = $this->socket->wsClients;
        foreach ($clients as $id => $client) {
            if ($id !== $clientId) {
                $this->socket->wsSend($id, "Visitor {$clientId} ({$ip}) has joined the room.");
            }
        }
    }

    public function onClose($clientId)
    {
        $ip = long2ip($this->socket->wsClients[$clientId][6]);

        $this->socket->log("{$ip} ({$clientId}) has disconnected.");

        $clients = $this->socket->wsClients;
        foreach ($clients as $id => $client) {
            if ($id !== $clientId) {
                $this->socket->wsSend($id, "Visitor {$clientId} ({$ip}) has left the room.");
            }
        }
    }

    public function onMessage($clientId, $message) {
        // 课件开课老师弹出层分页
        // web socket 实现
        $obj = json_decode($message);

        $partArgumentArr = [$obj->q];

        $html = userPagination($obj->page, $partArgumentArr, $obj->per_page);

        $this->socket->wsSend($clientId, $html);
        return;
        // 幻灯广告websocket版本分页
        $obj = json_decode($message);
        $argumentSeg = [$obj->q, $obj->is_lesson];
        $html = pagination($obj->page, $argumentSeg, $obj->per_page);
        $this->socket->wsSend($clientId, $html);
        return;
        $ip = long2ip($this->socket->wsClients[$clientId][6]);

        if (count($this->socket->wsClients) === 1) {
            $b = $this->socket->wsSend($clientId, "There isn't anyone else in the room, but I'll still listen to you. --Your Trusty Server");
            return;
        }

        $clients = $this->socket->wsClients;
        foreach ($clients as $id => $client) {
            if ($id !== $clientId) {
                $this->socket->wsSend($id, "Visitor {$clientId} ({$ip}) said {$message}");
            }
        }
    }
}

function userPagination($page, array $partArgument, $perPage = 15)
{
    $mysqli = connectMysql();

    list($q) = $partArgument;

    $offset = ($page - 1) * $perPage;

    $where = "WHERE m.username LIKE '%{$q}%' OR s.name LIKE '%{$q}%'";

    $total = $mysqli->query("SELECT COUNT(*) FROM fablab_member AS m LEFT JOIN fablab_school AS s ON m.school=s.id {$where}")
        ->fetch_row()[0];

    $lastPage = (int) ceil($total / $perPage);

    $pager = paginationDom($page, $lastPage);

    $sql = "SELECT m.uid,m.username,s.name AS school_name FROM fablab_member AS m LEFT JOIN fablab_school AS s ON m.school=s.id {$where} LIMIT {$perPage} OFFSET {$offset}";
    if ($result = $mysqli->query($sql)) {
        $html = assembleHtml($result);
    }

    return $html.$pager;
}

function assembleHtml($data)
{
    $html = '<table class="table table-striped table-bordered table-condensed"><thead><tr><th>ID</th><th>姓名</th><th>所属学校</th><th>操作</th></tr></thead><tbody>';

    while ($row = $data->fetch_assoc()) {
        $html .= '<tr><td>'.$row['uid'].'</td><td>'
            .$row['username'].'</td><td>'.$row['school_name']
            .'</td><td><input type="radio" class="td-radio-'
            .$row['uid'].'" name="choice" value="'.$row['uid'].'"></td></tr>';
    }

    $html .= '</tbody></table>';

    return $html;
}

function connectMysql()
{
    $mysqli = new mysqli('mpma.rootant.org', 'pro_fablab', '123456x', 'pro_fablab');

    if ($mysqli->connect_error) {
        die('Connect Error ('.$mysqli->connect_errno.') '.$mysqli->connect_error);
    }

    return $mysqli;
}

function countResutlRow($mysqli, $q, $isLesson)
{
    $countSql = "SELECT count(*) FROM fablab_course WHERE name LIKE \"%{$q}%\" AND is_lesson={$isLesson}";

    return $mysqli->query($countSql)->fetch_row()[0];
}

function pagination($page, array $argumentArr, $perPage = 20)
{
    $mysqli = connectMysql();

    list($q, $isLesson) = $argumentArr;

    $offset = ($page - 1) * $perPage;

    $total = countResutlRow($mysqli, $q, $isLesson);

    $lastPage = (int) ceil($total / $perPage);

    $pager = paginationDom($page, $lastPage);

    $html = '<input type="text" class="q" data="course">'
        .'<button class="btn search">搜索</button>'
        .'<button class="btn select">确认选择</button>'
        .'<table class="table table-striped table-bordered table-condensed">'
        .'<thead> <tr> <th>ID</th> <th>名称</th> <th>选择</th> </tr> </thead>'
        .'<tbody>';

    $sql = "SELECT id,name FROM fablab_course WHERE name LIKE \"%{$q}%\" AND is_lesson={$isLesson} LIMIT {$perPage} OFFSET {$offset}";
    if ($result = $mysqli->query($sql)) {
        while ($row = $result->fetch_assoc()) {
            $html .= '<tr><td>'.$row['id'].'</td><td>'.$row['name'].'</td><td><input type="radio" class="td-radio-'
                .$row['id'].'" name="choice" value="'.$row['id'].'"></td></tr>';
        }
        $html .= '</tbody></table>'.$pager;
    }

    return $html;
}

function paginationDom($currentPage, $lastPage, $pageLimit = 5)
{
    if ($currentPage > $lastPage) {
        $currentPage = $lastPage;
    }

    $limit = $currentPage + $pageLimit;
    if ($limit > $lastPage) {
        $limit = $lastPage + 1;
    }

    $prefixLi = '';
    if ($currentPage > 1) {
        $prefixLi = '<li><a class="page" href="javascript:;" data="'.($currentPage - 1).'">上一页</a></li>';
    }

    $li = '<li class="active"><a class="page" href="javascript:;" data="'.$currentPage.'">'.$currentPage.'</a></li>';
    if ($lastPage === 1) {
        $li = '';
    }
    for ($i = ($currentPage + 1); $i < $limit; $i++) {
        $li .= '<li><a class="page" href="javascript:;" data="'.$i.'">'.$i.'</a></li>';
    }

    $liSuffix = '';
    if ($limit < ($lastPage + 1)) {
        $liSuffix = '<li><a class="page" href="javascript:;" data="'.$limit.'">下一页</a></li>';
    }

    return '<ul class="pagination pagination-lg">'.$prefixLi.$li.$liSuffix.'</ul>';
}

$test = new TestWebSocket(new PHPWebSocket);

$test->binds([
    'open'    => array($test, 'onOpen'),
    'message' => array($test, 'onMessage'),
    'close'   => array($test, 'onClose'),
]);

$test->startServer('127.0.0.1', 9388);
